function GM_getValue(name, fallback) {
	return fallback;
}

// Register GM Commands and Methods
//if(!GM_registerMenuCommand) {
//	GM_registerMenuCommand( "Gmail Favicon Alerts > Chat Alerts On", function() { setChat(true) } );
//	GM_registerMenuCommand( "Gmail Favicon Alerts > Chat Alerts Off", function() { setChat(false) } );
//	GM_registerMenuCommand( "Gmail Favicon Alerts > Unread Count On", function() { setUnreadCountDisplay(true) } );
//	GM_registerMenuCommand( "Gmail Favicon Alerts > Unread Count Off", function() { setUnreadCountDisplay(false) } );
//	function setChat(val) { GM_setValue('chatEnabled', val) };
//	function setUnreadCountDisplay(val) { GM_setValue('unreadCountDisplay', val) };
//}

var gfia_instance = null;
var gfia_chat = GM_getValue('chatEnabled', true);
function addFunctionality(gfia) { };
var getUnreadImage = function() {
		if(!self.unreadImage) {
			self.unreadImage = document.createElement('img');
			icons = document.head.getElementsByTagName("link");
			var found = false;
			for(var i=icons.length - 1; i>=0; --i) {
				icon = icons[i];
				if(icon.rel.match(/^shortcut icon$/i)) {
					self.unreadImage.src = icon.href;
					found = true;
					break;
				}
			}
			if(!found) {
				for(var i=icons.length - 1; i>=0; --i) {
					icon = icons[i];
					if(icon.rel.match(/^icon$/i)) {
						self.unreadImage.src = icon.href;
						found = true;
						break;
					}
				}
			}
			if(!found) {
				self.unreadImage.src = "/favicon.ico";
			}
		}
		var url = self.unreadImage.src;
		var index = url.indexOf("://");
		index = url.indexOf("/",index+3);
		self.unreadImage.src = url.substr(index);
		return self.unreadImage;
	}

var gfia_icon = getUnreadImage();
var gfia_displayed = false;
var port = null;
var settings = {};
if(gfia_icon) {
//	chrome.extension.sendRequest({host: document.location.host, init: true}, function(response) {
//		if(response.enabled) {
//			gfia_instance = new FavIconAlerts(gfia_icon);
//		}
//	});
	port = chrome.extension.connect({host: document.location.host});
	port.onMessage.addListener(function(msg) {
		settings = msg;
		if(msg.enabled) {
			if(gfia_instance) {
				if(gfia_instance.enabled) {
					gfia_instance.forceUpdate();
				} else {
					gfia_instance.start();
				}
			} else {
				gfia_instance = new FavIconAlerts(gfia_icon);
			}
		} else if(msg.enabled === false) {
			if(!gfia_displayed) {
				port.postMessage({show:true});
				gfia_displayed = true;
			}
			if(gfia_instance) {
				if(gfia_instance.enabled) {
					gfia_instance.stop();
				}
			}
		}
	});
	port.postMessage({needReply: true});	
}

function FavIconAlerts(gfia_icon) {
	var self = this;
	self.unreadImage = gfia_icon;
	self.enabled = true;
	this.construct = function() {				
		this.chat = this.getChat();
		this.chatting = false;
		this.head = document.head;
		this.title = document.head.getElementsByTagName('title')[0];
		this.inboxText = 'Inbox';
		this.chatText = [
							{value:'\u2026', chars: 1},
							{value:'...', chars: 3}
						];
		
		timeout = -1000;
		
		if(this.title) {
			this.title.addEventListener('DOMSubtreeModified', this.poll, false);
		}
		if(document.location == 'http://www.p01.org/releases/DEFENDER_of_the_favicon/') {
			document.head.addEventListener('DOMSubtreeModified', this.iFrameTrick, false);
		}
		try {
			this.poll();
		} catch(exception) { }
		this.forceUpdate();
		addFunctionality(this);
		return true;
	}
	
	this.stop = function() {
		self.enabled = false;
		if(self.title) {
			self.title.removeEventListener('DOMSubtreeModified', self.poll, false);
		}
		self.forceUpdate();
	}
	
	this.start = function() {
		self.enabled = true;
		if(self.title) {
			self.title.addEventListener('DOMSubtreeModified', self.poll, false);
		}
		self.forceUpdate();
	}
	
	this.forceUpdate = function() {
		timeout += 1000;
		if(timeout == 5000 && self.unreadImage.height == 0) {
			self.unreadImage.src = "/favicon.ico";
		}
		try {
			if(self.poll()) {
				this.iFrameTrick();
				if(timeout < 10000) {
					setTimeout(self.forceUpdate, 1000);
				}
			}
		} catch(e) { }
	}
	this.shim = null;
	this.iFrameTrick = function() {
		if(!this.shim) {
			this.shim = document.createElement('iframe');
			this.shim.width = this.shim.height = 0;
			this.shim.style.cssText = "display:none;"
			document.body.appendChild(this.shim);
		}
		//if(this.shim.src != "about:blank")
		//	this.shim.src = "about:blank"
		//this.shim.src = "data:,";
		this.shim.src = "";
		//document.body.removeChild(this.shim);
		//document.body.appendChild(this.shim);
	}
	
	this.drawUnreadCount = function(unread, iconImage) {
		if(!iconImage) {
			iconImage = self.unreadImage;
			useCached = true;
		}
		var textedCanvas = document.createElement('canvas');
		textedCanvas.height = textedCanvas.width = 16;
		var ctx = textedCanvas.getContext('2d');
		ctx.drawImage(iconImage, 0, 0, 16, 16);
		
		drawUnread(textedCanvas, unread, settings);
		return textedCanvas;
	}
	this.getChat = function() { return false || GM_getValue('chatEnabled', true); }
	this.getDebugging = function() { return false || GM_getValue('debuggingEnabled', false); }
	this.getUnreadCountDisplay = function() { return GM_getValue('unreadCountDisplay', true); }
	this.getUnreadCount = function() {
		//matches = document.title.match(/\((\d+)\+?\)/);
		matches = document.title.match(/\((\d+)\+?(\s*unread)?\)/);
		return matches ? matches[1] : false;
	}
	this.getUnreadCountIcon = function() {
		var count = self.getUnreadCount();
		if(count) {
			if(!gfia_displayed) {
				port.postMessage({show:true});
				gfia_displayed = true;
			}
			return self.drawUnreadCount(count).toDataURL('image/png');
		} else {
			return self.unreadImage.src;
		}
	}
	this.poll = function() {
		var icon = self.enabled? self.getUnreadCountIcon() : self.unreadImage.src;
		self.setIcon(icon);
		return icon != self.unreadImage.src;
	};
	this.setIcon = function(icon) {
		var links = self.head.getElementsByTagName("link");
		var newIcon = null;
		for (var i = 0; i < links.length; i++)
			if(links[i].rel=="icon") {
				self.head.removeChild(links[i]);
			}
			else if (links[i].rel.match(/^shortcut icon$/i)) {
				newIcon = links[i];
				newIcon.type = "image/png";
				//newIcon.rel = "shortcut icon";
			}
		if(newIcon) {
			if(newIcon.href == icon) {
				return;
			}
		} else {
			newIcon = document.createElement("link");
			newIcon.type = "image/png";
			newIcon.rel = "shortcut icon";
			self.head.appendChild(newIcon);
		}
		newIcon.href = icon;
		
		this.iFrameTrick();
		//var shim = document.createElement('iframe');
		//shim.width = shim.height = 0;
		//document.body.appendChild(shim);
		//shim.src = "icon";
		//document.body.removeChild(shim);
	}
	
	this.toString = function() { return '[object GmailFavIconAlerts]'; }
	
	return this.construct();
}